package my.jwds.p25;

import my.jwds.p21.ListNode;

public class ReverseKGroup {

    public static void main(String[] args) {

        Solution obj = new Solution();
        long start = System.currentTimeMillis();
        System.out.println(obj.reverseKGroup(ListNode.to(new int[]{1,2,3,4,5}),10));
        System.out.println("运行时间:" + (System.currentTimeMillis() - start));
    }

    static class Solution {


        public ListNode reverseKGroup(ListNode head, int k) {
            ListNode node = null;
            ListNode res = null;
            ListNode last = head;
            ListNode first = head;
            int i = 0;
            while(head != null){
                ListNode temp = head.next;
                head.next = node;
                node = head;
                head = temp;
                if (++i == k){
                    if (res == null)res = node;
                    if (first != last){
                        last.next = node;
                    }
                    first.next = head;
                    last =first;
                    first = head;
                    if (!gtSize(first,k))break;
                    i=0;
                    node = null;

                }
            }
            return res;
        }

        boolean gtSize(ListNode node,int k){
            for (int i = 0; i < k; i++) {
                if (node == null)return false;
                node = node.next;
            }
            return true;
        }
    }
}